<template>
  <div class="note-editor">
    <!-- 笔记编辑器头部 -->
    <div class="editor-header">
      <div class="header-left">
        <el-button 
          v-if="showBackButton" 
          :icon="ArrowLeft" 
          @click="$emit('back')"
          text
        >
          返回
        </el-button>
        <h3 v-if="isEdit">编辑笔记</h3>
        <h3 v-else>新建笔记</h3>
      </div>
      <div class="header-right">
        <el-button @click="saveDraft" :loading="saving">
          保存草稿
        </el-button>
        <el-button type="primary" @click="saveNote" :loading="saving">
          {{ isEdit ? '更新笔记' : '创建笔记' }}
        </el-button>
      </div>
    </div>

    <!-- 笔记表单 -->
    <el-form :model="form" :rules="rules" ref="formRef" label-width="80px">
      <el-row :gutter="20">
        <el-col :span="16">
          <!-- 笔记标题 -->
          <el-form-item label="标题" prop="title">
            <el-input 
              v-model="form.title" 
              placeholder="请输入笔记标题"
              maxlength="200"
              show-word-limit
            />
          </el-form-item>

          <!-- 笔记内容 -->
          <el-form-item label="内容" prop="content">
            <div class="editor-container">
              <div class="editor-toolbar">
                <el-button-group>
                  <el-button 
                    :type="editorMode === 'edit' ? 'primary' : ''" 
                    @click="editorMode = 'edit'"
                    size="small"
                  >
                    编辑
                  </el-button>
                  <el-button 
                    :type="editorMode === 'preview' ? 'primary' : ''" 
                    @click="editorMode = 'preview'"
                    size="small"
                  >
                    预览
                  </el-button>
                  <el-button 
                    :type="editorMode === 'split' ? 'primary' : ''" 
                    @click="editorMode = 'split'"
                    size="small"
                  >
                    分屏
                  </el-button>
                </el-button-group>
              </div>
              
              <div class="editor-content" :class="editorMode">
                <!-- 编辑器 -->
                <div v-show="editorMode === 'edit' || editorMode === 'split'" class="edit-panel">
                  <el-input
                    v-model="form.content"
                    type="textarea"
                    placeholder="支持Markdown格式，开始记录你的学习心得..."
                    :rows="20"
                    resize="none"
                  />
                </div>
                
                <!-- 预览 -->
                <div v-show="editorMode === 'preview' || editorMode === 'split'" class="preview-panel">
                  <div class="markdown-preview" v-html="renderedContent"></div>
                </div>
              </div>
            </div>
          </el-form-item>
        </el-col>
        
        <el-col :span="8">
          <!-- 笔记设置 -->
          <div class="note-settings">
            <h4>笔记设置</h4>
            
            <!-- 笔记类型 -->
            <el-form-item label="类型">
              <el-select v-model="form.noteType" placeholder="选择笔记类型">
                <el-option label="普通笔记" value="GENERAL" />
                <el-option label="视频笔记" value="VIDEO_TIMESTAMP" />
                <el-option label="章节总结" value="CHAPTER_SUMMARY" />
                <el-option label="问题笔记" value="QUESTION" />
              </el-select>
            </el-form-item>

            <!-- 视频时间点 -->
            <el-form-item 
              v-if="form.noteType === 'VIDEO_TIMESTAMP'" 
              label="时间点"
            >
              <el-input-number 
                v-model="form.videoTimestamp" 
                :min="0" 
                placeholder="视频时间(秒)"
                class="timestamp-input"
              />
              <div class="timestamp-helper">
                {{ formatTimestamp(form.videoTimestamp) }}
              </div>
            </el-form-item>

            <!-- 标签 -->
            <el-form-item label="标签">
              <el-select
                v-model="form.tags"
                multiple
                filterable
                allow-create
                placeholder="选择或输入标签"
                no-data-text="输入新标签按回车添加"
              >
                <el-option
                  v-for="tag in popularTags"
                  :key="tag"
                  :label="tag"
                  :value="tag"
                />
              </el-select>
            </el-form-item>

            <!-- 公开设置 -->
            <el-form-item label="公开">
              <el-switch 
                v-model="form.isPublic"
                active-text="公开"
                inactive-text="私有"
              />
              <div class="help-text">
                公开的笔记可以被其他学员看到
              </div>
            </el-form-item>

            <!-- 关联课程 -->
            <el-form-item label="关联课程">
              <el-select 
                v-model="form.courseId" 
                placeholder="选择关联的课程（可选）"
                clearable
                filterable
                @change="onCourseChange"
                :loading="coursesLoading"
              >
                <el-option
                  v-for="course in availableCourses"
                  :key="course.id"
                  :label="course.title"
                  :value="course.id"
                />
              </el-select>
              <div class="help-text" v-if="form.courseId">
                关联课程后，笔记将与该课程关联显示
              </div>
            </el-form-item>
          </div>
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch, onMounted } from 'vue'
import { ElMessage, type FormInstance } from 'element-plus'
import { ArrowLeft } from '@element-plus/icons-vue'
import { notesApi, type Note, type NoteRequest } from '@/api/notes'
import { courseApi, type Course } from '@/api/course'
import { marked } from 'marked'

// Props
interface Props {
  noteId?: number
  courseId?: number
  lessonId?: number
  videoTimestamp?: number
  showBackButton?: boolean
}

const props = withDefaults(defineProps<Props>(), {
  showBackButton: true
})

// Emits
const emit = defineEmits<{
  back: []
  saved: [note: Note]
}>()

// 响应式数据
const formRef = ref<FormInstance>()
const saving = ref(false)
const editorMode = ref<'edit' | 'preview' | 'split'>('edit')
const popularTags = ref<string[]>([])

const form = ref<NoteRequest>({
  courseId: props.courseId || null,
  lessonId: props.lessonId,
  videoTimestamp: props.videoTimestamp,
  title: '',
  content: '',
  tags: [],
  noteType: 'GENERAL',
  isPublic: false
})

// 表单验证规则
const rules = {
  title: [
    { required: true, message: '请输入笔记标题', trigger: 'blur' },
    { max: 200, message: '标题不能超过200个字符', trigger: 'blur' }
  ],
  content: [
    { required: true, message: '请输入笔记内容', trigger: 'blur' }
  ]
}

// 计算属性
const isEdit = computed(() => !!props.noteId)

// Markdown渲染
const renderedContent = computed(() => {
  if (!form.value.content) return '<p class="empty-preview">内容预览将在这里显示...</p>'
  
  try {
    return marked(form.value.content)
  } catch (error) {
    return '<p class="error-preview">Markdown解析错误</p>'
  }
})

// 课程相关数据
const coursesLoading = ref(false)
const availableCourses = ref<Course[]>([])

// 加载用户的课程列表
const loadAvailableCourses = async () => {
  try {
    coursesLoading.value = true
    const response = await courseApi.getCourses({
      page: 1,
      pageSize: 100,
      sortBy: 'latest'
    })
    availableCourses.value = response.content || []
  } catch (error) {
    console.error('加载课程列表失败:', error)
    ElMessage.error('加载课程列表失败')
  } finally {
    coursesLoading.value = false
  }
}

// 课程变更处理
const onCourseChange = (courseId: number | null) => {
  if (courseId) {
    console.log('选择了课程:', courseId)
  }
}

// 方法
const formatTimestamp = (seconds?: number) => {
  if (!seconds) return '00:00'
  
  const hours = Math.floor(seconds / 3600)
  const minutes = Math.floor((seconds % 3600) / 60)
  const secs = seconds % 60
  
  if (hours > 0) {
    return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
  } else {
    return `${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
  }
}

const loadPopularTags = async () => {
  try {
    popularTags.value = await notesApi.getPopularTags(20)
  } catch (error) {
    console.error('加载常用标签失败:', error)
  }
}

const loadNote = async () => {
  if (!props.noteId) return
  
  try {
    const note = await notesApi.getNoteById(props.noteId)
    form.value = {
      courseId: note.courseId,
      lessonId: note.lessonId,
      videoTimestamp: note.videoTimestamp,
      title: note.title,
      content: note.content,
      tags: note.tags || [],
      noteType: note.noteType,
      isPublic: note.isPublic
    }
  } catch (error: any) {
    ElMessage.error(error.message || '加载笔记失败')
  }
}

const saveDraft = async () => {
  if (!formRef.value) return
  
  try {
    // 基本验证：至少需要标题
    if (!form.value.title.trim()) {
      ElMessage.warning('请输入笔记标题')
      return
    }
    
    saving.value = true
    
    // 创建草稿请求数据
    const draftData = {
      ...form.value,
      content: form.value.content || '(草稿内容)',
      title: form.value.title + (form.value.title.includes('(草稿)') ? '' : ' (草稿)')
    }
    
    let savedNote: Note
    if (isEdit.value && props.noteId) {
      savedNote = await notesApi.updateNote(props.noteId, draftData)
      ElMessage.success('草稿保存成功')
    } else {
      savedNote = await notesApi.createNote(draftData)
      ElMessage.success('草稿创建成功')
    }
    
    emit('saved', savedNote)
  } catch (error: any) {
    ElMessage.error(error.message || '草稿保存失败')
  } finally {
    saving.value = false
  }
}

const saveNote = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    saving.value = true
    
    let savedNote: Note
    if (isEdit.value && props.noteId) {
      savedNote = await notesApi.updateNote(props.noteId, form.value)
      ElMessage.success('笔记更新成功')
    } else {
      savedNote = await notesApi.createNote(form.value)
      ElMessage.success('笔记创建成功')
    }
    
    emit('saved', savedNote)
  } catch (error: any) {
    ElMessage.error(error.message || '保存失败')
  } finally {
    saving.value = false
  }
}

// 监听器
watch(() => props.noteId, () => {
  if (props.noteId) {
    loadNote()
  }
}, { immediate: true })

// 生命周期
onMounted(() => {
  loadNote()
  loadPopularTags()
  loadAvailableCourses()
})
</script>

<style scoped>
.note-editor {
  background: #fff;
  border-radius: 8px;
  overflow: hidden;
}

.editor-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 24px;
  border-bottom: 1px solid #e4e7ed;
  background: #fafafa;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 12px;
}

.header-left h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
}

.header-right {
  display: flex;
  gap: 12px;
}

:deep(.el-form) {
  padding: 24px;
}

.editor-container {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  overflow: hidden;
}

.editor-toolbar {
  padding: 8px 12px;
  background: #f5f7fa;
  border-bottom: 1px solid #e4e7ed;
}

.editor-content {
  display: flex;
  min-height: 500px;
}

.editor-content.edit .edit-panel {
  flex: 1;
}

.editor-content.preview .preview-panel {
  flex: 1;
}

.editor-content.split .edit-panel,
.editor-content.split .preview-panel {
  flex: 1;
}

.edit-panel :deep(.el-textarea__inner) {
  border: none;
  border-radius: 0;
  box-shadow: none;
  resize: none;
}

.preview-panel {
  border-left: 1px solid #e4e7ed;
  padding: 16px;
  overflow-y: auto;
  background: #fafafa;
}

.markdown-preview {
  line-height: 1.6;
}

.markdown-preview :deep(h1),
.markdown-preview :deep(h2),
.markdown-preview :deep(h3),
.markdown-preview :deep(h4),
.markdown-preview :deep(h5),
.markdown-preview :deep(h6) {
  margin-top: 24px;
  margin-bottom: 16px;
  font-weight: 600;
}

.markdown-preview :deep(p) {
  margin-bottom: 16px;
}

.markdown-preview :deep(code) {
  background: #f1f3f4;
  padding: 2px 4px;
  border-radius: 3px;
  font-family: 'SFMono-Regular', Consolas, 'Liberation Mono', Menlo, monospace;
}

.markdown-preview :deep(pre) {
  background: #f6f8fa;
  padding: 16px;
  border-radius: 6px;
  overflow-x: auto;
}

.empty-preview,
.error-preview {
  color: #909399;
  font-style: italic;
  text-align: center;
  padding: 40px;
}

.error-preview {
  color: #f56c6c;
}

.note-settings {
  background: #f9f9f9;
  padding: 20px;
  border-radius: 6px;
}

.note-settings h4 {
  margin: 0 0 20px 0;
  font-size: 16px;
  font-weight: 600;
}

.timestamp-input {
  width: 100%;
}

.timestamp-helper {
  margin-top: 8px;
  font-size: 12px;
  color: #909399;
}

.help-text {
  margin-top: 8px;
  font-size: 12px;
  color: #909399;
}

.course-info {
  margin-top: 24px;
}

.course-info h5 {
  margin: 0 0 12px 0;
  font-size: 14px;
  font-weight: 600;
}

.course-item {
  padding: 12px;
  background: #fff;
  border-radius: 4px;
  border: 1px solid #e4e7ed;
}

.course-title {
  font-weight: 500;
  margin-bottom: 4px;
}

.lesson-title {
  font-size: 12px;
  color: #909399;
}
</style>




